package com.swing.games.snake.pages;

import com.swing.assets.Iurl;
import com.swing.games.snake.component.KeyBoard;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

/**
 * @author Yuang, Gongming
 * @date 2022-02-10 11:13
 */
public class Index extends JPanel implements ActionListener {

    int WIDTH = 600;
    int HEIGHT = 600;
    static int UNIT_SIZE = 20;

    public static volatile Timer timer;
    Random random = new Random();

    public Index() {
        timer = new Timer(1000, this);
//        this.setBackground(Color.LIGHT_GRAY);
        this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        ImageIcon image = null;
        try {
            image = new ImageIcon(new URL(Iurl.WALL_1));
            image.setImage(image.getImage().getScaledInstance(20, 20, Image.SCALE_AREA_AVERAGING));
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
        this.setBorder(BorderFactory.createMatteBorder(20, 20, 20, 20, image));
        this.addKeyListener(new KeyBoard());
        //  游戏开始后

        timer.start();

//        try {
//            Thread.sleep(10000);
//            timer.stop();
//        } catch (Exception e1) {
//            //  ignore
//        }

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("build - paintComponent");
        //  snake SNAKE
        try {
            Thread.sleep(100);
        }catch (Exception e){
            //
        }
        g.fillRect(random.nextInt(300), random.nextInt(300), UNIT_SIZE, UNIT_SIZE);

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        System.out.println(this.getClass() + " - " + System.currentTimeMillis());
//        this.setSize(random.nextInt(600), random.nextInt(600));


    }
}
